<?php
namespace Admin\Model;
use Think\Model,
    Admin\Model\AclModel;

class AuthModel extends Model
{
    public $errorMsg = array(
        1=>'验证码错误',
        2=>'用户不存在',
        3=>'用户被禁用',
        4=>'密码错误'
    );

    public $successMsg = array(
        1=>'登录成功'
    );

    /**
     * 登录
     *
     * @param array $post 必须包含 array('username', 'password')
     *
     * @return array
     */
    public function login($post)
    {
        $m_acl = new AclModel();
        $info = $m_acl->getTableAclAdmin(4, array('admin_name'=>$post['username']));
        if($info)
        {
            //用户状态
            $st = intval($info['st']);
            if($st === 0)
            {
                return array('st'=>'err', 'msg'=>$this->errorMsg[3]);
            }
            //密码
            if($info['admin_password'] === my_encode($post['password']))
            {
                session('admin_id', intval($info['admin_id']));
                session('admin_group_id', intval($info['admin_group_id']));
                session('admin_name', $info['admin_name']);
                session('admin_acl', $info['admin_acl']);
                session('idle', time()+C('SESSION_IDLE'));
                if($info['admin_name']==='root' && intval($info['admin_id'])===1){
                    // root账号
                    session('root', true);
                }else{
                    session('root', false);
                    // 非root账号，记录下权限
                    $auths = $m_acl->getAclNode(2, array('st'=>1, 'node_ids'=>$info['admin_acl']), 'node_id,m_c_a');
                    $acls = array();
                    if($auths){
                        foreach($auths as $au){
                            $acls[$au['node_id']] = $au['m_c_a'];
                        }
                        $acls = array_unique($acls);
                    }
                    session('auth', $acls);
                }
                return array('st'=>'ok', 'msg'=>$this->successMsg[1]);
            }
            else
            {
                return array('st'=>'err', 'msg'=>$this->errorMsg[4]);
            }
        }
        else
        {
            return array('st'=>'err', 'msg'=>$this->errorMsg[2]);
        }
    }
}